package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;


@RestControllerAdvice(annotations = {RestController.class, Controller.class})
@Slf4j
@Component
public class GlobalExeptionHandler {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> handlerSQLConstraintException(SQLIntegrityConstraintViolationException ex){
            // 1、打印异常信息 log.error()  getMessage
            String message = ex.getMessage();
            log.error(message);
            // 2、获取异常信息 getMessage()  Duplicate entry '111' for key 'idx_username'
            // 3、判断异常信息是唯一约束异常  contains("Duplicate entry")
            if (message.contains("Duplicate entry")){
                  //违反的是唯一约束
                  //3.1、如果是，获取异常信息中的用户名 split  replace ，返回 xxx已存在
                  String[] split = message.split("'");
                  return R.error( "账号名：" + split[1] + "已存在");
            }
             //3.2、如果不是，返回 “数据异常！！”
            return R.error("数据异常");
    }

    @ExceptionHandler(BusinessException.class)
    public R handlerBusinessException(BusinessException exception){
        log.error(exception.getMessage());
        return R.error(exception.getMessage());
    }
}
